from fastapi import APIRouter, HTTPException, Depends, status, Request
from sqlalchemy.orm import Session
from database import get_db
from models import UserLogin, LoginResponse, UserResponse
from auth import authenticate_user, create_session, get_current_user, logout_session

router = APIRouter()

@router.post("/login", response_model=LoginResponse)
async def login(user_login: UserLogin, db: Session = Depends(get_db)):
    user = authenticate_user(user_login.username, user_login.password, db)
    
    if not user:
        return LoginResponse(
            success=False,
            message="用户名或密码错误"
        )
    
    session_id = create_session(user.username)
    
    return LoginResponse(
        success=True,
        message="登录成功",
        user=UserResponse(
            id=user.id,
            username=user.username,
            name=user.name,
            role=user.role
        ),
        token=session_id
    )

@router.get("/me", response_model=UserResponse)
async def get_current_user_info(current_user = Depends(get_current_user)):
    return UserResponse(
        id=current_user.id,
        username=current_user.username,
        name=current_user.name,
        role=current_user.role
    )

@router.post("/logout")
async def logout(request: Request):
    authorization = request.headers.get("Authorization")
    if authorization:
        try:
            scheme, session_id = authorization.split()
            if scheme.lower() == "bearer":
                logout_session(session_id)
        except ValueError:
            pass
    
    return {"success": True, "message": "登出成功"}

@router.post("/refresh")
async def refresh_token(current_user = Depends(get_current_user)):
    new_session_id = create_session(current_user.username)
    
    return {
        "success": True,
        "message": "令牌刷新成功",
        "token": new_session_id
    }